/*
 * Classname Challenge.java
 *
 * Version information
 *
 * Date Mar 14, 2006
 * Copyright (c) AmSoft Systems, 2006
 */
package net.amsoft.iservice.isso.webapp.struts.action;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.ResourceBundle;

import net.amsoft.iservice.isso.hibernate.Principal;
import net.amsoft.iservice.isso.hibernate.PrincipalMetaData;
import net.amsoft.iservice.isso.service.ISSOService;
import net.amsoft.iservice.isso.util.ISSOConstants;
import static net.amsoft.iservice.isso.util.ISSOConstants.*;
import net.amsoft.iservice.util.EmailService;
import net.amsoft.iservice.util.IServiceConstants;
import net.amsoft.iservice.util.IServiceUtil;
import net.amsoft.iservice.util.exception.IServiceException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

/**
 * @author mohit
 */
public class Challenge extends BaseAction {
	public static Logger oLogger = Logger.getLogger(Challenge.class);
	public ActionForward process(ActionMapping oMapping, ActionForm oForm,
			HttpServletRequest oRequest, HttpServletResponse oResponse)
			throws Exception {
		oLogger.info("process() : entry");
		// Get values from request parameters
		String sRecoveryAnswer = oRequest.getParameter(REQ_PARAM_RECOVERY_ANS);
		String sGlobalINumber = oRequest.getParameter(REQ_PARAM_GINU);
		String sChallengeQuestion = oRequest
				.getParameter(REQ_PARAM_CHALLENGE_QUEST);

		ActionMessages oMessages = new ActionErrors();
		try {
			if (ISSOService.verifyChallengeAnswer(sGlobalINumber,
					sRecoveryAnswer)) {
				oLogger.info("process() : AnswerVerify=success");	
				// Generated random password
				String sRandPwd = IServiceUtil.generateUniqueID();
				sRandPwd = sRandPwd.substring(0, 7);
				// Update principal profile
				ISSOService
						.updatePassword(sGlobalINumber, null, null, sRandPwd);
				oLogger.info("process() : message : PasswordUpdated, creating email");
				
				/*
				 * Create email to send randomly generated password
				 */
				ResourceBundle oBundle = ResourceBundle.getBundle(
						"issoResources", oRequest.getLocale());
				String sPattern = oBundle.getString(EMAIL_BODY);
				String sUrl = oRequest.getScheme() + "://"
						+ oRequest.getServerName();
				Object[] params = {sRandPwd, sUrl};
				String sCompleteMsg = MessageFormat.format(sPattern, params);
				String sDefaultFromAddr = IServiceConstants.ISERVICE_BUNDLE
						.getString(IServiceConstants.EMAIL_FROM);

				// Get Email address of the subscriber
				Principal oPrincipal = ISSOService.getPrincipalProfile(
						sGlobalINumber, null);
				PrincipalMetaData oPrincipalData = ISSOService
						.getMetaData(oPrincipal);
				ArrayList<String> alRecepientList = new ArrayList<String>();
				alRecepientList.add(oPrincipalData.getEmail());
				
				// Create email object
				EmailService oEmailService = new EmailService();
				oEmailService.setFromAddress(sDefaultFromAddr);
				oEmailService.setReplyToAddress(sDefaultFromAddr);
				oEmailService.setName(oBundle.getString(SENDER_NAME));

				oEmailService.setReceipientList(alRecepientList);
				oEmailService.setBody(sCompleteMsg);
				oEmailService.setSubject(oBundle.getString(EMAIL_SUBJECT));
				oEmailService.sendMail();

				oLogger.info("process() : Message : Email sent. Pwd updated. Exit");
				oMessages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
						MSG_PASSWORD_UPDATED));

				// Forward to login page with message.
				saveErrors(oRequest, oMessages);
				return oMapping.findForward(INAME_FWD);
			} else {
				oLogger.warn("process() : Message : Password does not match");
				oMessages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
						ERR_INCORRECT_ANSWER));
			}
		} catch (IServiceException ise) {
			oMessages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
					getError(ise.getErrorCode()), false));
		}

		// Set request parameters
		oRequest.setAttribute(ISSOConstants.REQ_PARAM_CHALLENGE_QUEST,
				sChallengeQuestion);
		oRequest.setAttribute(ISSOConstants.REQ_PARAM_GINU, sGlobalINumber);

		// Forward to login page with message.
		saveErrors(oRequest, oMessages);
		return oMapping.getInputForward();
	}
}